<template>
		<view class="shop-car">
			<shop-cart :list="cartsList" @goodsCheck="goodsCheck" 
				@setAllCheck="setAllCheck" @open="open" @click="click"
				@accounts="accounts">
			</shop-cart>
				
				
			<u-modal v-model="show" content="确认删除？" :show-cancel-button="true" :mask-close-able="true" 
				@confirm="delConfirm">
			</u-modal>
		</view>
</template>

<script>
export default {
	data() {
		return {
			cartsList: [],
				// 删除确认框
				show: false,
				delIndex: 0
		};
	},
	onShow() {
		this.getData()
	},
	methods: {
		async getData() {
			if(this.$u.utils.isLogin()){
				const resp = await this.$u.api.cartsList({include: 'goods'});
				// this.cartsList = resp.data
				// this.cartsList.map((val, idx) => {
				// 	val.show = false
				// })
				this.cartsList = resp.data.map((val, idx) => {
					val.show = false
					return val;
				});
			}
		},
		// 选中商品
		goodsCheck(indexq){
			let is_checked = this.cartsList[indexq].is_checked;
			//如果为已选中，则切换为未选中
			if(is_checked === 1){
				this.cartsList[indexq].is_checked = 0;
			}
			//如果为未选中，则切换为已选中
			if(is_checked === 0){
				this.cartsList[indexq].is_checked = 1;
			}
			this.checkChange()
		},
		// 选中状态改变
		async checkChange(){
			let idArr = this.cartsList.filter(item => item.is_checked == 1).map((val) => {
				return val.id
			})
			await this.$u.api.cartsChecked({cart_ids:idArr})
		},
		//全选
		setAllCheck(allCheck){
			// 当前为全选，则需执行的操作为：把状态为已选中的切换为未选中
			if(allCheck){
				this.cartsList.forEach((item) => {
					if(item.is_checked == 1){
						item.is_checked = 0
					}
				})
			}else{
				// 当前为非全选，则需执行的操作为：把状态为未选中的切换为已选中
				this.cartsList.forEach((item) => {
					if(item.is_checked == 0){
						item.is_checked = 1
					}
				})
			}
			this.checkChange()
		},
		// 如果打开一个的时候，不需要关闭其他，则无需实现本方法
		open(index) {
			// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
			// 原本为'false'，再次设置为'false'会无效
			this.cartsList[index].show = true;
			// this.$set(this.cartsList[index], 'show', true)
			this.cartsList.map((val, idx) => {
				if(index != idx) this.cartsList[idx].show = false;
				// if(index != idx) this.$set(this.cartsList[idx], 'show', false)
			})
		},
		
		//删除点击
		async click(index) {
			this.delIndex = index;
			this.showModal()
		},
		showModal() {
			this.show = true;
		},
		//确认删除
		async delConfirm(){
			let del = this.cartsList.splice(this.delIndex, 1);
			await this.$u.api.cartsDel(del[0].id);
			this.$u.toast('删除成功');
		},	
		/**
		 * 结算
		 */
		accounts(){
			this.$u.route({
				type: 'navigateTo',
				url: 'pages/order/orderPrew'
			})
		}
	}
};
</script>

<style lang="scss" scoped>
	.shop-car {
		width: 750rpx;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		align-items: center;
		background: #F5F5F5;
	}
</style>
